/**
 * AI Copilot 侧边栏组件
 * 显示实时建议、质量评分等信息
 */

import React, { useState, useEffect, useCallback } from 'react';
import { Card, Space, Tag, Button, Progress, List, Tooltip, Empty, Spin } from 'antd';
import {
  BulbOutlined,
  ThunderboltOutlined,
  FileTextOutlined,
  BarChartOutlined,
  CheckCircleOutlined,
  QuestionCircleOutlined,
  RightOutlined,
} from '@ant-design/icons';
import { aiCopilotService } from '@/services/ai-copilot.service';
import { CopilotSuggestion } from '@/types/brainstorm';
import './style.css';

interface CopilotSidebarProps {
  sessionId: string;
  selectedText?: string;
  beforeText?: string;
  afterText?: string;
  cursorPosition?: number;
  onApplySuggestion?: (suggestion: CopilotSuggestion) => void;
}

interface QualityMetrics {
  overall: number;
  originality: number;
  readability: number;
  information: number;
  emotion: number;
}

export const CopilotSidebar: React.FC<CopilotSidebarProps> = ({
  sessionId,
  selectedText = '',
  beforeText = '',
  afterText = '',
  cursorPosition = 0,
  onApplySuggestion,
}) => {
  const [suggestions, setSuggestions] = useState<CopilotSuggestion[]>([]);
  const [qualityScore, setQualityScore] = useState<QualityMetrics | null>(null);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<'suggestions' | 'quality'>('suggestions');

  // 初始化Copilot连接
  useEffect(() => {
    aiCopilotService.initCopilot(sessionId);

    // 监听Copilot事件
    const handleSuggestion = (event: CustomEvent) => {
      setSuggestions(prev => [...prev, event.detail]);
    };

    const handleQuality = (event: CustomEvent) => {
      setQualityScore(event.detail);
    };

    window.addEventListener('copilot-suggestion', handleSuggestion as EventListener);
    window.addEventListener('copilot-quality', handleQuality as EventListener);

    return () => {
      window.removeEventListener('copilot-suggestion', handleSuggestion as EventListener);
      window.removeEventListener('copilot-quality', handleQuality as EventListener);
      aiCopilotService.cleanup();
    };
  }, [sessionId]);

  // 获取建议
  const fetchSuggestions = useCallback(async () => {
    if (!selectedText && !beforeText) return;

    setLoading(true);
    try {
      const newSuggestions = await aiCopilotService.getSuggestions({
        selectedText,
        beforeText,
        afterText,
        cursorPosition,
      });
      setSuggestions(newSuggestions);
    } catch (error) {
      console.error('Failed to get suggestions:', error);
    } finally {
      setLoading(false);
    }
  }, [selectedText, beforeText, afterText, cursorPosition]);

  // 当文本变化时获取新建议
  useEffect(() => {
    const debounceTimer = setTimeout(() => {
      fetchSuggestions();
    }, 500);

    return () => clearTimeout(debounceTimer);
  }, [fetchSuggestions]);

  // 获取质量评分
  useEffect(() => {
    const text = selectedText || beforeText + afterText;
    if (text.length > 50) {
      aiCopilotService.getQualityScore(text).then(setQualityScore);
    }
  }, [selectedText, beforeText, afterText]);

  // 渲染建议图标
  const renderSuggestionIcon = (type: string) => {
    const iconMap: Record<string, React.ReactNode> = {
      expand: <RightOutlined />,
      add_example: <FileTextOutlined />,
      add_data: <BarChartOutlined />,
      add_transition: <ThunderboltOutlined />,
      simplify: <CheckCircleOutlined />,
      fix_grammar: <QuestionCircleOutlined />,
      improve_clarity: <BulbOutlined />,
    };
    return iconMap[type] || <BulbOutlined />;
  };

  // 渲染优先级标签
  const renderPriorityTag = (priority: string) => {
    const colorMap: Record<string, string> = {
      high: 'red',
      medium: 'orange',
      low: 'blue',
    };
    return <Tag color={colorMap[priority]}>{priority}</Tag>;
  };

  // 渲染建议列表
  const renderSuggestions = () => {
    if (loading) {
      return (
        <div className="copilot-loading">
          <Spin tip="正在分析..." />
        </div>
      );
    }

    if (suggestions.length === 0) {
      return (
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description="暂无建议"
          style={{ padding: '20px 0' }}
        >
          <p style={{ fontSize: '12px', color: '#999' }}>
            选择文本或继续写作以获取AI建议
          </p>
        </Empty>
      );
    }

    return (
      <List
        dataSource={suggestions}
        renderItem={(suggestion) => (
          <List.Item
            className="suggestion-item"
            actions={[
              <Button
                key="apply"
                type="link"
                size="small"
                onClick={() => onApplySuggestion?.(suggestion)}
              >
                应用
              </Button>,
            ]}
          >
            <List.Item.Meta
              avatar={<div className="suggestion-icon">{renderSuggestionIcon(suggestion.type)}</div>}
              title={
                <Space>
                  <span>{suggestion.title}</span>
                  {renderPriorityTag(suggestion.priority)}
                </Space>
              }
              description={suggestion.description}
            />
          </List.Item>
        )}
      />
    );
  };

  // 渲染质量评分
  const renderQualityScore = () => {
    if (!qualityScore) {
      return (
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description="暂无评分"
          style={{ padding: '20px 0' }}
        />
      );
    }

    const getScoreColor = (score: number) => {
      if (score >= 80) return '#52c41a';
      if (score >= 60) return '#faad14';
      return '#ff4d4f';
    };

    return (
      <div className="quality-score">
        <div className="overall-score">
          <Progress
            type="circle"
            percent={qualityScore.overall}
            strokeColor={getScoreColor(qualityScore.overall)}
            format={(percent) => (
              <div className="score-text">
                <div className="score-number">{percent}</div>
                <div className="score-label">综合评分</div>
              </div>
            )}
            width={120}
          />
        </div>

        <div className="score-breakdown">
          <div className="score-item">
            <span className="score-label">原创性</span>
            <Progress
              percent={qualityScore.originality}
              strokeColor={getScoreColor(qualityScore.originality)}
              size="small"
            />
          </div>
          <div className="score-item">
            <span className="score-label">可读性</span>
            <Progress
              percent={qualityScore.readability}
              strokeColor={getScoreColor(qualityScore.readability)}
              size="small"
            />
          </div>
          <div className="score-item">
            <span className="score-label">信息量</span>
            <Progress
              percent={qualityScore.information}
              strokeColor={getScoreColor(qualityScore.information)}
              size="small"
            />
          </div>
          <div className="score-item">
            <span className="score-label">情感度</span>
            <Progress
              percent={qualityScore.emotion}
              strokeColor={getScoreColor(qualityScore.emotion)}
              size="small"
            />
          </div>
        </div>

        <div className="score-tips">
          <h4>改进建议：</h4>
          {qualityScore.readability < 60 && (
            <p>• 简化句子结构，使用更通俗的词汇</p>
          )}
          {qualityScore.information < 60 && (
            <p>• 添加更多具体信息和细节</p>
          )}
          {qualityScore.emotion < 60 && (
            <p>• 加入更多生动的描述和情感元素</p>
          )}
          {qualityScore.originality < 60 && (
            <p>• 增加独特观点，避免陈词滥调</p>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="copilot-sidebar">
      <Card
        title={
          <Space>
            <BulbOutlined />
            <span>AI Copilot</span>
          </Space>
        }
        className="copilot-card"
        tabList={[
          {
            key: 'suggestions',
            tab: '智能建议',
          },
          {
            key: 'quality',
            tab: '质量评分',
          },
        ]}
        activeTabKey={activeTab}
        onTabChange={(key) => setActiveTab(key as 'suggestions' | 'quality')}
      >
        {activeTab === 'suggestions' ? renderSuggestions() : renderQualityScore()}
      </Card>

      <div className="copilot-tips">
        <h4>快捷操作：</h4>
        <ul>
          <li>
            <kbd>Tab</kbd> 接受补全建议
          </li>
          <li>
            <kbd>//</kbd> 唤醒指令菜单
          </li>
          <li>
            <kbd>Ctrl+Space</kbd> 显示建议
          </li>
        </ul>
      </div>
    </div>
  );
};